package com.humngyang.com.hmy.study.concurrency.myannoations.aqs;


import com.humngyang.com.hmy.study.concurrency.myannoations.ThreadSafe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;


/*
 *  利用readLock和WriteLock锁实现一个的map，可以利用读锁和写锁实现map集合的读写安全。但是这个是悲观锁，
 *  读的时候不允许有写锁还在进行，写锁的时候，不能有读锁进行
 *
 */

//线程安全的
@ThreadSafe
public class ReentrantReadWriteLockExample {
    private static Logger log = LoggerFactory.getLogger(ReentrantReadWriteLockExample.class);

    private final Map<String, Data> map = new TreeMap<>();

    private final ReentrantReadWriteLock rl = new ReentrantReadWriteLock();
    //读锁
    private final Lock readLock = rl.readLock();
    //写锁
    private final Lock writeLock = rl.writeLock();

    public Data get(String key) {
        readLock.lock();
        try {
            return map.get(key);
        } finally {
            readLock.unlock();
        }
    }

    public Set<String> getAllkeys() {
        readLock.lock();
        try {
            return map.keySet();
        } finally {
            readLock.unlock();
        }
    }

    public Data put(String key, Data value) {
        writeLock.lock();
        try {
            return map.put(key, value);
        } finally {
            writeLock.unlock();
        }
    }

    public class Data {

    }
}
